package cn.tedu.eguser1.controller;

import cn.tedu.eguser1.base.config.response.JsonResult;
import cn.tedu.eguser1.base.config.response.StatusCode;
import cn.tedu.eguser1.mapper.UserMapper;
import cn.tedu.eguser1.pojo.dto.UserAddParam;
import cn.tedu.eguser1.pojo.dto.UserLoginParam;
import cn.tedu.eguser1.pojo.dto.UserUpdateParam;
import cn.tedu.eguser1.pojo.entity.User;
import cn.tedu.eguser1.pojo.vo.UserListVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Slf4j
@Validated
@RestController
@Tag(name = "用户模块")
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/add")
    @Operation(summary = "添加用户")
    @ApiOperationSupport(order = 10)
    public JsonResult add(@RequestBody @Validated UserAddParam userAddParam) {
        User user = new User();

        BeanUtils.copyProperties(userAddParam, user);

        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        int i = userMapper.insert(user);

        if (i > 0) {
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }

    }

    @GetMapping("/list")
    public JsonResult list(){

        List<UserListVo> list =  userMapper.select();

        return JsonResult.ok(list);

    }

    @PostMapping("/del/{id}")
    @Operation(summary = "删除用户")
    @ApiOperationSupport(order = 20)
    public JsonResult del(@Pattern(regexp = "^(100|[1-9]?\\d)$",message = "用户id必须在1-100之间") @PathVariable Long id) {
        System.out.println("id" + id);

        int i = userMapper.delById(id);

        if (i > 0) {
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
    }

    @PostMapping("/update")
    public JsonResult update(@RequestBody UserUpdateParam userUpdateParam) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateParam, user);

        user.setUpdateTime(new Date());

        int i = userMapper.update(user);

        if (i > 0) {
            return JsonResult.ok();
        }else {
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }

    }

    @PostMapping("/login")
    public String login(@RequestBody UserLoginParam userLoginParam) {
        System.out.println("userLoginParam" + userLoginParam);
        return "登录成功";
    }


}
